package com.sc.service;

import com.sc.dao.OrderDao;
import com.sc.dao.OrderItemDao;
import com.sc.dao.ProductDao;
import com.sc.dao.impl.OrderDaoImpl;
import com.sc.dao.impl.OrderItemDaoImpl;
import com.sc.dao.impl.ProductDaoImpl;
import com.sc.entity.*;

import java.util.List;

public class OrderService {
    private static final OrderDao orderDao=new OrderDaoImpl();
    private static final ProductDao productDao=new ProductDaoImpl();
    private final static OrderItemDao orderItemDao=new OrderItemDaoImpl();
    /**
     * 购物车
     * @param user  用户
     * @param cartItems  购物车信息
     */
    public void order(User user, List<CartItem> cartItems) throws Exception {
        Order order=new Order();
        order.setStatus(1);
        //钱
        double sum=0.0;
        for (CartItem item:cartItems){
           sum+=item.getPrice();
        }
        order.setTotalPrice(0D);
        order.setUserId(user.getId());
        orderDao.add(order);
        //select * from 'order' where user_id = 1 order by create_time desc limit 1
        order=orderDao.findByUserIdAndLast(user.getId());
        for (CartItem cartItem:cartItems){
            OrderItem orderItem=new OrderItem();
            orderItem.setProductNum(cartItem.getProductNum());
            orderItem.setPrice(cartItem.getPrice());
            orderItem.setProductId(cartItem.getProductId());
            orderItem.setOrderId(order.getId());
            orderItemDao.add(orderItem);
            Product product = productDao.query(cartItem.getProductId());
            //减库存的操作
            product.setAmount(product.getAmount()-cartItem.getProductNum());
            productDao.update(product);
        }

    }

    /**
     * 直接购买
     * @param user 用户
     * @param product 商品
     * @param num 数量
     *
     * status 1 已下单
     */

    public synchronized void order(User user,Product product,int num) throws Exception {
        if (num<1){
            throw new RuntimeException("商品数量不能小于1");
        }
        if (product.getAmount()<num){
            throw new RuntimeException("库存不足");
        }
        Order order=new Order();
        order.setStatus(1);
        order.setTotalPrice(product.getPrice() * num);
        order.setUserId(user.getId());
        orderDao.add(order);
        //select * from 'order' where user_id = 1 order by create_time desc limit 1
        order=orderDao.findByUserIdAndLast(user.getId());
        //订单的商品加入
        OrderItem orderItem=new OrderItem();
        orderItem.setOrderId(order.getId());
        orderItem.setPrice(product.getPrice()*num);
        orderItem.setProductId(product.getId());
        orderItem.setProductNum(num);
        orderItemDao.add(orderItem);
        //减库存的操作
        product.setAmount(product.getAmount()-num);
        productDao.update(product);

    }

}
